
import os
import codecs
import tempfile


def safestr(strp, escape=True, hexa=True, html=False):
    ret = ''
    if escape or html:
        hexa = True

    for k in str('' if strp is None else strp):
        v = ord(k)
        if 32 <= v < 127:
            ret += k
        elif v == 0x0a and escape:
            ret += '\\r'
        elif v == 0x0d and escape:
            ret += '\\n'
        elif hexa:
            if html:
                ret += '#%02x' % v
            else:
                ret += '\\x%02x' % v

    return ret


def withConsole(file_name):
    # check the extension for the console
    basename = os.path.basename(file_name)
    extname = os.path.splitext(file_name)[1].lower()

    if extname in ('.py', '.pyc', '.pyo'):
        isConsole = True
    elif basename == 'aof.exe':
        isConsole = True
    else:
        isConsole = False

    return isConsole


def testDirectoryWriteable(path):
    try:
        fd, fname = tempfile.mkstemp(dir=path)
        os.close(fd)
        os.unlink(fname)

        return True
    except IOError:
        return False


def _expandNameWithUnderline(list_):
    """ build up new names from the given name:
    get_name -> getName -> GetName"""

    expanded = list()
    for li in list_:
        nname, capital = '', False
        for c in li.lower():
            if c == '_':
                capital = True
            elif capital:
                nname += c.upper()
                capital = False
            else:
                nname += c

        if len(nname) > 0:
            cname = nname[0].upper() + nname[1:]
            if cname not in expanded:
                expanded.append(cname)

        if nname not in expanded:
            expanded.append(nname)

        expanded.append(li)

    return expanded


def hasAttrs(class_, list_):
    ret = False

    for intf in _expandNameWithUnderline(list_):
        if hasattr(class_, intf):
            ret = True
            break

    return ret


def getAttrFromMethods(class_, list_, default=None, *args, **kws):
    ret = default

    for intf in _expandNameWithUnderline(list_):
        if hasattr(class_, intf):
            func = getattr(class_, intf)
            if len(args) > 0:
                if len(kws.keys()) > 0:
                    ret = func(*args, **kws)
                else:
                    ret = func(*args)
            else:
                if len(kws.keys()) > 0:
                    ret = func(**kws)
                else:
                    ret = func()

            break

    return ret


def int2rgb(int_val):
    return ((int_val >> 16) & 0xff, (int_val >> 8) & 0xff, int_val & 0xff)


def rgb2int(rgb_val):
    return ((rgb_val[0] * 256) + rgb_val[1]) * 256 + rgb_val[2]


def openfile(filename, mode, utf8=False):
    try:
        if utf8:
            return codecs.open(filename, mode, 'utf-8')
        else:
            return open(filename, mode)
    except IOError:
        return None


def si(val, base=16, default=-1):
    try:
        return int(val, base)
    except ValueError:
        return default


def atoi(str_, little_endian=True, **kws):
    def _reverse(s):
        r = ''
        for c in s:
            r = c + r
        return r

    if '_endian' in kws:
        little_endian = kws['_endian']

    if little_endian:
        str_ = _reverse(str_)

    ret = 0
    for c in str_:
        ret = ret * 256 + ord(c)

    return ret


def getString(str_, deli=0x00):
    ret = ''
    for c in str_:
        if ord(c) != deli:
            ret += c
        else:
            break

    return ret
